package com.doudou.oauth.handler;


import com.doudou.commons.entity.Result;
import com.doudou.commons.utils.BrowserUtils;
import com.doudou.oauth.constant.SysConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** 
* @Description: 认证失败的逻辑处理
* @author: 傻男人
* @Date: 2019\10\29
*/
@Component
public class FailLoginHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    ObjectMapper objectMapper;

    /**
     * 认证失败的逻辑处理
     * @param request
     * @param response
     * @param exception
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if(BrowserUtils.isBrowser(request)){
            System.out.println("-----------登录失败----------");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType(SysConstant.JSON_CONTENT_TYPE);
            response.getWriter().write(objectMapper.writeValueAsString(Result.fail(exception.getMessage())));
        }else {
            super.onAuthenticationFailure(request,response,exception);
        }

    }
}
